package sign_in.loginsystem.service.realize;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sign_in.loginsystem.mapper.DepartmentMapper;
import sign_in.loginsystem.mapper.UserMapper;
import sign_in.loginsystem.model.util.Result;
import sign_in.loginsystem.model.entity.User;
import sign_in.loginsystem.service.port.AccountService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class ControlsAccountService implements AccountService {

    @Resource
    UserMapper userMapper;

    @Resource
    DepartmentMapper departmentMapper;



    @Transactional
    @Override
    public boolean registerAccount(User user) {

        User search = userMapper.search(user.getUserName(), user.getPassword());
        if (search!=null){
            return false;
        }
        user.setDepartment(4);


        boolean sure = userMapper.createUser(user);
        userMapper.insertRoleAndUser(user);
        if (sure){
            departmentMapper.setUpDepartmentUser(user);
        }
        return sure;
    }

    @Override
    public Result editAccount(User analyzed, User user) {
        User search = userMapper.search(analyzed.getUserName(), analyzed.getPassword());
        if (search==null){
            return Result.error(null);
        }
        user.setId(search.getId());
        if(!Objects.equals(search.getDepartment(), user.getDepartment())){
            departmentMapper.editDepartmentUser(user);
        }
        userMapper.edit(user);
        return login(user);
    }
    @Override
    public boolean delete(User user) {
        User search = userMapper.search(user.getUserName(), user.getPassword());
        user.setId(search.getId());
        departmentMapper.deleteDepartmentUser(user);
        return userMapper.delete(user.getUserName(), user.getPassword());
    }

    @Override
    public Result login(User user) {
        User search = userMapper.search(user.getUserName(), user.getPassword());
        String token;
        if(search==null){
            return Result.fail(search);
        }

        Map<String, String> claim = new HashMap<>();
        claim.put("username",user.getUserName());
        claim.put("password",user.getPassword());

        JWTCreator.Builder builder = JWT.create();
        builder.withExpiresAt(new Date(System.currentTimeMillis()+3600*1000)).withPayload(claim);
        token = builder.sign(Algorithm.HMAC256("iosLaboratory"));

        return Result.success(token);
    }
}
